package com.cn.jdia.springmvc.handlers;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import org.joda.time.DateTime;
import org.joda.time.Duration;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.google.gson.Gson;

@Controller
public class PeccancyController {

	@RequestMapping("/peccancyctrl")
	public String insertPeccancy(HttpServletRequest request, HttpServletResponse response) throws IOException {

		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();

		String date = request.getParameter("date");
		String content = request.getParameter("content");
		String person = request.getParameter("person");

		DateTime datetime = new DateTime();
		String nowDate = datetime.toString("YYYY-MM-dd:hh-mm-ss");

		@SuppressWarnings("resource")
		ClassPathXmlApplicationContext w_context = new ClassPathXmlApplicationContext("springmvc.xml");
		DataSource ds = (DataSource) w_context.getBean("dataSource2");

		int res = 0;

		try {
			Connection conn = ds.getConnection();
			Statement st = conn.createStatement();

			StringBuffer sb = new StringBuffer("INSERT INTO ATT_PECCANCY VALUES('").append(date).append("','")
					.append(nowDate).append("','").append(content).append("','").append(person).append("','admin')");
			System.out.println(sb.toString());
			res = st.executeUpdate(sb.toString());

			System.out.println("Result:" + res);
			st.close();
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	
		out.write(res + "");
		out.flush();
		out.close();

		return null;
	}

	@RequestMapping("/productctrl")
	public String insertProduct(HttpServletRequest request, HttpServletResponse response) throws IOException {

		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();

		String date = request.getParameter("date");
		String jiaci = request.getParameter("jiaci");
		String lvke = request.getParameter("lvke");
		String huoyou = request.getParameter("huoyou");
		String fangxing = request.getParameter("fangxing");
		String zhixing = request.getParameter("zhixing");
		String hangban = request.getParameter("hangban");

		DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
		String dataDate = date + " 08:01:25";
		DateTime datetime = DateTime.parse(dataDate, format);
		DateTime nextDate = datetime.plusDays(1);
		System.out.println(date + " , " + jiaci + " , " + lvke + " , " + huoyou + " , " + fangxing);
		String nextdate = nextDate.toString("yyyy-MM-dd HH:mm:ss");

		@SuppressWarnings("resource")
		ClassPathXmlApplicationContext w_context = new ClassPathXmlApplicationContext("springmvc.xml");
		DataSource ds = (DataSource) w_context.getBean("dataSource2");

		int res = 0;

		try {
			Connection conn = ds.getConnection();
			Statement st = conn.createStatement();

			StringBuffer isNew = new StringBuffer(
					"select * from FORMMAIN_6250_AOC where to_char(MODIFY_DATE,'YYYY-MM-DD') like '")
							.append(nextDate.toString("YYYY-MM-dd")).append("%'");
			System.out.println(isNew.toString());
			ResultSet newRs = st.executeQuery(isNew.toString());
			int count = 0;
			while (newRs.next()) {
				count++;
			}

			if (count == 0) {
				StringBuffer sb = new StringBuffer("insert into FORMMAIN_6250_AOC values(to_date('").append(nextdate)
						.append("','yyyy-mm-dd hh24:mi:ss'),to_date('").append(dataDate)
						.append("','yyyy-mm-dd hh24:mi:ss'),").append(jiaci).append(",").append(lvke).append(",")
						.append(huoyou).append(",'2017','").append(hangban).append("','").append(fangxing).append("','")
						.append(zhixing).append("')");
				System.out.println(sb.toString());
				res = st.executeUpdate(sb.toString());

			} else {
				StringBuffer up = new StringBuffer("update FORMMAIN_6250_AOC set FIELD0002=").append(jiaci)
						.append(",FIELD0003=").append(lvke).append(",FIELD0004=").append(huoyou).append(",FIELD0007='")
						.append(fangxing).append("',FIELD0008='").append(zhixing).append("',FIELD0006='")
						.append(hangban).append("' where to_char(MODIFY_DATE,'YYYY-MM-DD') like '")
						.append(nextDate.toString("YYYY-MM-dd")).append("%'");
				System.out.println(up.toString());
				res = st.executeUpdate(up.toString());
			}
			System.out.println("Result:" + res);

			st.close();
			conn.close();

		} catch (SQLException e) {
			e.printStackTrace();
		}

		out.write(res + "");
		out.flush();
		out.close();

		return null;

	}

	@RequestMapping("/updatePecInfo")
	public String updatePecInfo(HttpServletRequest request, HttpServletResponse response) throws IOException {
		System.out.println("update pec info");

		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();

		String json = request.getParameter("strJson");
		System.out.println(json);

		Gson gson = new Gson();

		@SuppressWarnings("unchecked")
		Map<String, String> map = gson.fromJson(json, HashMap.class);
		System.out.println(map);

		String date = map.get("Date");
		String subject = map.get("SubjectName");
		String content = map.get("Content");
		String id = map.get("id");

		System.out.println(id);
		System.out.println(date);
		System.out.println(subject);
		System.out.println(content);

		// DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MM-dd");
		// DateTime datetime = DateTime.parse(date, format);
		// DateTime nowDate = new DateTime();
		//
		// System.out.println(datetime);
		// System.out.println(nowDate);
		//
		// Duration du = new Duration(datetime, nowDate);
		// long days = du.getStandardDays();
		//
		// System.out.println("days:" + days);
		//
		// // do nothing
		// if (days > 2) {
		// out.write("-1");
		// } else {

		// update
		@SuppressWarnings("resource")
		ClassPathXmlApplicationContext w_context = new ClassPathXmlApplicationContext("springmvc.xml");
		DataSource ds = (DataSource) w_context.getBean("dataSource2");

		try {
			Connection conn = ds.getConnection();
			Statement st = conn.createStatement();

			StringBuffer sb = new StringBuffer("UPDATE ATT_PECCANCY SET CONTENT='").append(content)
					.append("' WHERE CREATTIME='").append(id).append("'");

			int ret = st.executeUpdate(sb.toString());
			System.out.println("Ret:" + ret);

			st.close();
			conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		out.close();

		return null;
	}

}
